package com.zboot.comm.datasource.sharding.appender;

import org.apache.shardingsphere.sharding.rule.TableRule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 所有appender统一的代理服务
 * 提供了一个dispatch方法，根据规则分发到对应的真实服务
 */
@Service("shardingDataNodeAppenderAgent")
public class ShardingDataNodeAppenderAgent implements ShardingDataNodeAppender {

    //追加器map，key=逻辑表名 value=appender对象
    private Map<String, ShardingDataNodeAppender> appenderMap = new HashMap<>();

    @Autowired
    public ShardingDataNodeAppenderAgent(ShardingDataNodeAppender... appders) {
        //注册到追加器map
        for (ShardingDataNodeAppender appder : appders) {
            appenderMap.put(appder.getLogicTableName(), appder);
        }
    }

    @Override
    public String getLogicTableName() {
        return null;
    }

    @Override
    public boolean needAppend(TableRule tableRule) {
        return this.dispatch(tableRule.getLogicTable()).needAppend(tableRule);
    }

    @Override
    public void append(TableRule tableRule) {
        this.dispatch(tableRule.getLogicTable()).append(tableRule);
    }

    /**
     * 根据逻辑表名，获取到对应的appender
     */
    private ShardingDataNodeAppender dispatch(String logicTableName) {
        return this.appenderMap.get(logicTableName);
    }
}
